package timing.ukulele.flow.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.flow.mapper.FlowMapper;
import timing.ukulele.persistent.service.BaseService;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.ResultCode;
import timing.ukulele.common.flow.FlowData;
import timing.ukulele.common.item.ItemData;
import timing.ukulele.common.portal.SystemData;
import timing.ukulele.flow.client.ItemClient;
import timing.ukulele.flow.client.SystemClient;
import timing.ukulele.flow.dictionary.FlowStatusEnum;
import timing.ukulele.flow.persistent.Flow;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class FlowService extends BaseService<FlowMapper, Flow> {

    @Resource
    private SystemClient systemClient;
    @Resource
    private ItemClient itemClient;

    /**
     * 获取分页
     *
     * @param current 当前也页，从1开始
     * @param size    每页大小
     * @return 模板数据
     */
    public IPage<Flow> getPage(String system, int current, int size, HashMap<String, Object> map) {
        Page<Flow> page = new Page<>(current, size);
        LambdaQueryWrapper<Flow> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Flow::getId);
        if (map.get("name") != null) {
            qw.like(Flow::getName, map.get("name"));
        }
        if (map.get("modelId") != null) {
            qw.like(Flow::getFlowKey, map.get("modelId"));
        }

        if (map.get("systemId") != null) {
            qw.like(Flow::getSystemId, map.get("systemId"));
        }
        qw.orderByDesc(Flow::getId);
        //对sytemName的模糊查询
        final ResponseResult<List<SystemData>> responseResult;
        if (map.get("systemName") != null) {
            responseResult = systemClient.getLikeSystemName((String) map.get("systemName"));
        } else {
            responseResult = systemClient.all();
        }
        //获取业务系统id的集合
        List<Long> systemIdList = new ArrayList<>();
        if (responseResult.getData() != null) {
            responseResult.getData().stream().forEach(e -> systemIdList.add(e.getId()));
        }
        if (!CollectionUtils.isEmpty(systemIdList)) {
            qw.in(Flow::getSystemId, systemIdList);
        }

        List<Long> mySystemIds;
        if (!"".equals(system)) {
            String[] split = system.split(",");
            if (!"0".equals(split[0])) {
                mySystemIds = Arrays.asList(split).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                qw.in(Flow::getSystemId, mySystemIds);
            }
        }
        IPage<Flow> iPage = getBaseMapper().selectPage(page, qw);
        Map<Long, String> systemNameMap = null;
        if (responseResult != null && !CollectionUtils.isEmpty(responseResult.getData())) {
            systemNameMap = responseResult.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
        }
        if (!CollectionUtils.isEmpty(systemNameMap)) {
            List<Flow> flowList = iPage.getRecords();
            if (flowList != null && flowList.size() > 0) {
                for (Flow flow : flowList) {
                    flow.setSystemName(systemNameMap.get(flow.getSystemId()));
                }
            }
        }
        return iPage;
    }

    public IPage<Flow> getPageBySystemId(Long systemId, int current, int size, Integer status, Integer active) {
        Page<Flow> page = new Page<>(current, size);
        LambdaQueryWrapper<Flow> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Flow::getId);
        //默认是部署
        if (status != null) {
            qw.eq(Flow::getStatus, status);
        } else {
            qw.eq(Flow::getStatus, FlowStatusEnum.PUBLISHED);
        }
        //默认是启用
        if (active != null) {
            qw.eq(Flow::getActive, active);
        } else {
            qw.eq(Flow::getActive, 1);
        }
        if (systemId != null) {
            qw.eq(Flow::getSystemId, systemId);
        }
        IPage<Flow> iPage = getBaseMapper().selectPage(page, qw);
        return iPage;
    }

    public List<FlowData> getBySystemId(Long systemId) {
        Map<String, Object> params = new HashMap<>();
        params.put("system_id", systemId);
        List<Flow> flows = getBaseMapper().selectByMap(params);
        List<FlowData> flowDatas = new ArrayList<>();
        if (!CollectionUtils.isEmpty(flows)) {
            for (Flow flow : flows) {
                FlowData flowData = new FlowData();
                BeanUtils.copyProperties(flow, flowData);
                flowDatas.add(flowData);
            }
        }
        return flowDatas;
    }


    public ResponseResult<List<ItemData>> getFlowItems(Long flowId) {
        ResponseResult<List<ItemData>> items = itemClient.getItemByFlowId(flowId);
        if (items == null || ResultCode.SUCCESS.getCode() != items.getCode()) {
            return ResponseResult.rpcError("获取流程绑定的事项出错!");
        }
        return ResponseResult.success(items.getData());
    }

}
